﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Request.Line;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Infrastructure.EFCore;
using WCS.Infrastructure.IOC;
using WCS.Infrastructure.Tools;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    [Inject]
    public class LineService : BaseService, ILineService
    {
        private readonly IConfiguration _configuration;
        private readonly LineIOC _lineIOC;
        private readonly IUserService _userService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public LineService(IConfiguration configuration, LineIOC lineIOC, IUserService userService, IHttpContextAccessor httpContextAccessor)
        {
            _configuration = configuration;
            _lineIOC = lineIOC;
            _userService = userService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 新增线路打卡记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddLinePunchRecordAsync(LinePunchRecordCreateRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var userId = dto.UserId ?? _httpContextAccessor.HttpContext?.GetCurrentUserId() ?? string.Empty;
                LinePunchRecord linePunchRecord = new LinePunchRecord
                {
                    Id = Config.GUID(),
                    UserId = userId,
                    LineId = dto.LineId,
                    StartTime = dto.StartTime,
                    EndTime = dto.EndTime,
                    ExtraProperties = dto.ExtraProperties,
                    CreationTime = DateTime.Now
                };

                await _lineIOC._linePunchRecordEFCore.AddAsync(linePunchRecord);
                var result = await _lineIOC._linePunchRecordEFCore.SaveChangesAsync();

                if (result == 0)
                {
                    return GetResult(0, "创建打卡记录失败，请稍后再试！");
                }

                scope.Complete();
                return GetResult(1);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 更新线路打卡记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="lineId"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateLinePunchRecordAsync(LinePunchRecordCreateRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var userId =dto.UserId ?? _httpContextAccessor.HttpContext?.GetCurrentUserId() ?? string.Empty;

                var linePunchRecord = await _lineIOC._linePunchRecordEFCore.QueryAll(d => d.UserId == userId && d.LineId == dto.LineId).FirstOrDefaultAsync();

                if (linePunchRecord == null)
                {
                    return GetResult(0, "未找到打卡记录，无法完成打卡！");
                }

                linePunchRecord.ExtraProperties = dto.ExtraProperties;
                linePunchRecord.EndTime = DateTime.Now;

                await _lineIOC._linePunchRecordEFCore.UpdateAsync(linePunchRecord);
                var result = await _lineIOC._linePunchRecordEFCore.SaveChangesAsync();
                if (result == 0)
                {
                    return GetResult(0, "更新线路打卡失败，请稍后再试！");
                }

                scope.Complete();
                return GetResult(1);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取线路打卡记录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="lineId"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetLinePunchRecordAsync(string? userId, string lineId)
        {
            try
            {
                userId = userId ?? _httpContextAccessor.HttpContext?.GetCurrentUserId() ?? string.Empty;

                var linePunchRecord = await _lineIOC._linePunchRecordEFCore.QueryAll(d => d.UserId == userId && d.LineId == lineId).FirstOrDefaultAsync();

                return GetResult(1, data:linePunchRecord);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
